package com.lwj.diao.Utils;

import com.lwj.diao.StringSourceJavaObject;

import java.io.Writer;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class UtilClass {
    public static String parseClassName(String content) {
        String packageName = "";
        String className = null;
        int packageStart = content.indexOf("package");
        int packageEnd = content.indexOf(";", packageStart);
        if (packageStart >= 0 && packageEnd > 0) {
            packageName = content.substring(packageStart += "package".length(), packageEnd).replace('\t', ' ').trim() + ".";
        }
        int classStart = content.indexOf("class");
        int classEnd = content.indexOf("{", classStart);
        if (classStart >= 0 && classEnd > 0) {
            className = content.substring(classStart += "class".length(), classEnd).replace('\t', ' ').trim();
        }
        return packageName + className;
    }

    public static boolean compile(String className, String source, Writer out) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        StringSourceJavaObject sourceObject = new StringSourceJavaObject(className, source);
        List<StringSourceJavaObject> fileObjects = Arrays.asList(sourceObject);
        LinkedList<String> options = new LinkedList<String>();
        options.add("-d");
        options.add(UtilJar.getJarDir() + "dcls/");
        JavaCompiler.CompilationTask task = compiler.getTask(out, fileManager, null, options, null, fileObjects);
        return task.call();
    }
}
